//
//  LGTRWZPublicVC.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/20.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit
import WisdomHUD
import IQKeyboardManagerSwift

 //请按要求输入文字内容

class LGTRWZPostVC: LGTBaseVC, UITableViewDelegate, UITableViewDataSource, HJImageBrowserDelegate{
    
    //请按要求输入文字内容
    var postParamModel:PostParamModel?
    var tableView:UITableView?
    var data:Array<Array<Dictionary<String, Any?>>> = Array.init()
    var cellAddStepBlock:ClickPathBlock? //添加步骤
    var stepCellClickBlock:ClickStepPathBlock? //步骤的cell点击处理
    var cellRetunrStrBlock:ClickCellStrBlock?
    var typeSelectBlock:ClickPostNameModelBlock?  //请选择类型 操作系统选择
    var stepInfoSaveBlock:ClickInfoBlock? // 保存步骤回掉
    var addStepView:UIImageView?
    var stepArray:Array<Dictionary<String, Any?>> = [] //步骤信息
    var clearData:Bool = false // 清除数据处理  发布成功清楚数据
    
    //参数保存
    var submitDataInfo2:Dictionary<String, Any?> = ["type":nil, //选择类型
        "os":nil,  //支持设备
        "projectName":"", //项目名称
        "taskRequest":"", //任务要求
        "workTime":nil, //做单时间
        "reviewTime":nil, //审核时间
        "workTimes":nil, //做单次数
        "workPrice":"", //任务单价
        "taskCount":"", //任务数量
        "toptime":"", //置顶天数
        "offline":"", //下线时间
        "step":[],//添加步骤
        "payMoney":0.0, //总共花费点费用
        "topPrice":0.0 //置顶钱
    ]
    
    //索引 几组几行
    var pathKeyInfo:Dictionary<String, Any> = ["0,0":"type",
                                            "1,0":"os",
                                            "2,0":"projectName",
                                            "2,1":"taskRequest",
                                            "2,2":"workTime",
                                            "2,3":"reviewTime",
                                            "2,4":"workTimes",
                                            "3,0":"workPrice",
                                            "3,1":"taskCount",
                                            "4,0":"toptime",
                                            "4,1":"offline",
                                            "5,0":"step"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.getData()
        self.setBlock()
        NotificationCenter.default.addObserver(self, selector: #selector(wxPaySuccessAction), name: WXPay_ReCharge_Note, object: nil)
    }
    
    //数据清理
    @objc func wxPaySuccessAction(note:Notification){
        //支付完成回掉
        self.clearData = true
        //数据清理
        rwz_saveSubmitModel(info: [:])
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: WXPay_ReCharge_Note, object: nil)
    }
    
    override func setUI(){
        super.setUI()
        //代码太多分一下出去
        self.setUIAdd()
    }
    
    func setBlock(){
        weak var weakSelf = self
        self.reloadBlock = {
            () -> Void in
            weakSelf?.getData()
        }
        
        self.typeSelectBlock = {(data:PostNameModel, path:IndexPath) -> Void in
            let pathKey:String = "\(path.section),\(path.row)"
            let keyValue:String = weakSelf?.pathKeyInfo[pathKey] as? String ?? ""
            var reload:Bool = true
            if path.section == 0{
                 reload = false
                //刷新任务单价 、任务数量的提示语 是否需要处理
            }else if path.section == 1{
                reload = false
            }
            weakSelf?.submitDataInfo2[keyValue] = data
            //下限时间
            if path.section == 4{
                weakSelf?.submitDataInfo2[keyValue] = data.name
            }
            weakSelf?.initData(reload: reload)
        }
        
        //cell返回字符串
        self.cellRetunrStrBlock = {(text:String, path:IndexPath) -> Void in
            let pathKey:String = "\(path.section),\(path.row)"
            let keyValue:String = weakSelf?.pathKeyInfo[pathKey] as? String ?? ""
            weakSelf?.submitDataInfo2[keyValue] = text
            var reload:Bool = false
            weakSelf?.initData(reload: reload)
            //需支付的价格刷新
            if path.section == 3 || path.section == 4{
                weakSelf?.tableView?.reloadRows(at: [IndexPath.init(row: 0, section: 5)], with: UITableView.RowAnimation.none)
            }
        }
        
        //添加步骤处理
        self.cellAddStepBlock = { (data:Any, path:IndexPath) -> Void in
            let dict:Dictionary<String, Any> = data as? Dictionary ?? [:]
           // if path.section == 6{
                //显示添加步骤视图
            //let path:IndexPath? = data["path"] as? IndexPath
            //if path ==
                let view:UIView = dict["addButton"] as! UIView
                weakSelf?.showStepView(view:view)
            //}
        }
        
        //保存步骤点击回掉
        self.stepInfoSaveBlock = {(index:Int, info:Dictionary<String, Any>) -> Void in
            var path:IndexPath? = info["path"] as? IndexPath
            if path != nil{
                //更新操作
                let row:Int = path!.row - 1
                self.stepArray[row] = info
            }else{
                weakSelf?.stepArray.append(info)
            }
            weakSelf?.initData(reload: true)
        }
        
        //步骤上的cell 点击
        self.stepCellClickBlock = {(data:Dictionary<String, Any>, path:IndexPath,  index:Int, view:UIView?) -> Void in
            let row:Int = path.row - 1
            var reloadState:Bool = true
            switch index {
            case StepCellClickType.delete.rawValue:  //删除
                self.stepArray.remove(at: row)
                break
                
            case StepCellClickType.movedonw.rawValue:  //下移动
                if row == ((weakSelf?.stepArray.count)! - 1){
                    return
                }
                self.stepArray.swapAt(row, row+1)
                break
                
            case StepCellClickType.moveup.rawValue:  //上移动
                if row == 0{
                    return
                }
                 self.stepArray.swapAt(row, row-1)
                break
                
            case StepCellClickType.edit.rawValue:  //编辑
                //显示添加步骤视图
                let viewIndex:Int = data["index"] as? Int ?? 0
                var newData:Dictionary<String, Any> = data
                newData["path"] = path
                weakSelf?.gotoStepDetailVC(index: viewIndex, info: newData)
                reloadState = false
                break
                
            case StepCellClickType.openurl.rawValue: //打开链接
                let url:String = data["subText"] as? String ?? ""
                let gotoURL:URL? = URL.init(string: url)
                if gotoURL != nil{
                    UIApplication.shared.open(gotoURL!, options: [:], completionHandler: nil)
                }
                reloadState = false
                break
                
            case StepCellClickType.copyurl.rawValue: //复制链接
                let url:String = data["subText"] as? String ?? ""
                UIPasteboard.general.string = url
                WisdomHUD.showSuccess(text: "复制成功")
                reloadState = false
                break
                
            case StepCellClickType.ImageBrower.rawValue:
                let imageInfo:Dictionary<String, Any> = data["selectInfo"] as? Dictionary<String, Any> ?? [:]
                let bview = HJImageBrowser()
                bview.delegate = self
                bview.bottomView = view!
                bview.indexImage = 0
                bview.defaultImage = getColorImageWithColor()
                let url:String = imageInfo["url"] as? String ?? ""
                bview.arrayImage = [url]
                bview.show()
                break
            
            default:
                break
            }
            weakSelf?.initData(reload: reloadState)
            }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.data.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let array = self.data[section]
        return array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let array:Array<Dictionary<String, Any>> = self.data[indexPath.section]
        let info = array[indexPath.row]
        let input:Bool = info["input"] as? Bool ?? false
        let typeSelect:Bool = info["typeSelect"] as? Bool ?? false
        let option:Bool = info["option"] as? Bool ?? false
        let pay:Bool = info["pay"] as? Bool ?? false
        let addStep:Bool = info["addStep"] as? Bool ?? false
        let ruler:Bool = info["ruler"] as? Bool ?? false
        let collection:Bool = info["collection"] as? Bool ?? false
        let isurl:Bool = info["isurl"] as? Bool ?? false
        let imageAndText:Bool = info["imageAndText"] as? Bool ?? false
        let stepHead:Bool = info["stepHead"] as? Bool ?? false
        
        if input == true{
            let cell:LGTRWZPostInputCell = tableView.dequeueReusableCell(withIdentifier: "inputCell", for: indexPath) as! LGTRWZPostInputCell
            cell.model = info
            cell.path = indexPath
            cell.returnStrBlock = cellRetunrStrBlock
            return cell
        }else if typeSelect == true{
            let cell:LGTRWZPostTypeCell = tableView.dequeueReusableCell(withIdentifier: "typeCell", for: indexPath) as! LGTRWZPostTypeCell
            cell.path = indexPath
            cell.typeSelectBlock = self.typeSelectBlock
            cell.model = info
            return cell
        }else if option == true{
            let cell:LGTRWZPostOptionCell = tableView.dequeueReusableCell(withIdentifier: "optionCell", for: indexPath) as! LGTRWZPostOptionCell
            cell.model = info
            cell.path = indexPath
            cell.returnStrBlock = cellRetunrStrBlock
            return cell
        }else if pay == true{
            let cell:LGTRWZPostPayCell = tableView.dequeueReusableCell(withIdentifier: "payCell", for: indexPath) as! LGTRWZPostPayCell
            cell.model = info
            return cell
        }
        //添加步骤
        else if addStep == true{
            let cell:LGTRWZPostAddStepCell = tableView.dequeueReusableCell(withIdentifier: "addStepCell", for: indexPath) as! LGTRWZPostAddStepCell
            cell.path = indexPath
            cell.clickBlock = self.cellAddStepBlock
            cell.model = info
            return cell
        }
        //规则
        else if ruler == true{
            let cell:LGTRWZPostRulerCell = tableView.dequeueReusableCell(withIdentifier: "rulerCell", for: indexPath) as! LGTRWZPostRulerCell
            return cell
        }
        //复制 和 收集
        else if collection == true{
            let cell:LGTRWZCopyStepCell = tableView.dequeueReusableCell(withIdentifier: "copyCell", for: indexPath) as! LGTRWZCopyStepCell
            cell.path = indexPath
            cell.model = info
            cell.stepCellClickBlock = self.stepCellClickBlock
                return cell
        }
        //打开url
        else if isurl == true{
            let cell:LGTRWZUrlStepCell = tableView.dequeueReusableCell(withIdentifier: "urlCell", for: indexPath) as! LGTRWZUrlStepCell
            cell.path = indexPath
            cell.model = info
            cell.stepCellClickBlock = self.stepCellClickBlock
            return cell
        }
        //图片
        else if imageAndText == true{
            let cell:LGTRWZImageTextStepCell = tableView.dequeueReusableCell(withIdentifier: "imagetextcell", for: indexPath) as! LGTRWZImageTextStepCell
            cell.path = indexPath
            cell.model = info
            cell.stepCellClickBlock = self.stepCellClickBlock
            return cell
        }
        //操作步骤头部
        else if stepHead == true{
             let cell:LGTStepTitleViewCell = tableView.dequeueReusableCell(withIdentifier: "stepHeadCell", for: indexPath) as! LGTStepTitleViewCell
            return cell
        }
        else{
            let cell:LGTRWZPostSelectCell = tableView.dequeueReusableCell(withIdentifier: "selectCell", for: indexPath) as! LGTRWZPostSelectCell
            cell.model = info
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let key:String =  "\(indexPath.section),\(indexPath.row)"
        let valueKey:String = self.pathKeyInfo[key] as? String ?? "'"
        if indexPath.section == 2{
            if indexPath.row == 0 || indexPath.row == 1{
                return 
            }
            
            
            let keyValue:String! = self.pathKeyInfo[key] as? String
            if keyValue?.count == 0 || keyValue == nil{
                return
            }
            
            let vc:LGTRWZCommenSelectVC = LGTRWZCommenSelectVC()
            let data:Array<PostNameModel> = self.postParamModel?.dataInfo?[valueKey] ?? Array.init()
            vc.data = data
            vc.currentModel = self.submitDataInfo2[valueKey] as? PostNameModel
            vc.clickBlock = self.typeSelectBlock
            vc.modalPresentationStyle = .overCurrentContext
            vc.path = indexPath
            self.navigationController!.present(vc, animated: false, completion: nil)
        }
        
        //选择时间
        if indexPath.section == 4 && indexPath.row == 1{
            let vc:LGTRWZTimeSelectVC = LGTRWZTimeSelectVC()
            vc.modalPresentationStyle = .overCurrentContext
            vc.clickBlock = self.typeSelectBlock
            vc.path = indexPath
            vc.currentDateStr = self.submitDataInfo2["offline"] as? String ?? ""
            self.navigationController!.present(vc, animated: false, completion: nil)
        }
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view:UIView = UIView.init()
        view.backgroundColor = ViewBackColor
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == self.data.count - 1{
            //return SizeFitFloat(8)
            return CGFloat(TabBarH())
        }
        return SizeFitFloat(8)
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
        self.addStepView?.isHidden = true
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enable = false
    }
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //BaseUtil.baseUtil.testsss(info: self.submitDataInfo2)
        self.submitDataInfo2["step"] = self.stepArray
        rwz_saveSubmitModel(info: self.submitDataInfo2)
        IQKeyboardManager.shared.enable = true
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if self.clearData == true{
            rwz_saveSubmitModel(info: [:])
        }
    }
    
    func getTheThumbnailImage(_ indexRow: Int) -> UIImage {
        return UIImage.init()
    }

}
